package com.tangyuan.user.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.constant.RedisConstant;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.util.CommStatus;
import com.tangyuan.common.util.MD5;
import com.tangyuan.common.util.NameConverter;
import com.tangyuan.model.User;
import com.tangyuan.model.UserLike;
import com.tangyuan.user.mapper.UserMapper;
import com.tangyuan.user.service.IUserService;
import com.tangyuan.vo.UserMayKnowVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: user
 * @Author: jeecg-boot
 * @Date: 2024-03-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getUserById(Long userId) {
        return this.getById(userId);
    }

    @Override
    public boolean setUserById(String key, Object value, String token) {
        User user = CommStatus.getUser(token);
        Integer integer = baseMapper.setUserById(key, value, user.getId());
        try {
            if (integer > 0) {
                Class<?> clazz = user.getClass();
                Field field = clazz.getDeclaredField(NameConverter.convertToCamelCase(key));
                field.setAccessible(true);
                // 赋值
                field.set(user, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        CommStatus.set(CommStatus.joinToken(token), user, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        return integer > 0;
    }

    @Override
    public UserLike getUserLikeByUserId(Long userId) {
        return userMapper.getUserLikeByUserId(userId);
    }

    @Override
    public void deleteUserVideoCollectionByVideoId(Long videoId) {
        userMapper.deleteUserVideoCollectionByVideoId(videoId);
    }

    @Override
    public void deleteUserActionByVideoId(Long videoId) {
        userMapper.deleteUserActionByVideoId(videoId);
    }

    @Override
    public List<User> getUserListByLastSql(String lastSql) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 1);
        queryWrapper.orderBy(true, true, "RAND()");
        queryWrapper.last(lastSql);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public Result saveRobotNum(String param) {
        int count = 10;
        if (!param.isEmpty()) {
            try {
                count = Integer.parseInt(param);
            } catch (NumberFormatException e) {
                throw new RuntimeException(e);
            }
        }
        List<User> users = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            //验证码正确 注册新用户
            User user = new User();
            //生成一个随机数用作用户id
            String randomNumber = String.valueOf(System.currentTimeMillis()).substring(5, 13);
            //设置时间
            user.setCreateTime(new Date());
            user.setMobile(generateRandomMobilePhoneNumber());
            //设置用户id
            user.setAccount(randomNumber);
            //密码加密
            user.setPassword(MD5.encrypt("123456"));
            //添加用户默认昵称
            user.setName("唐园" + RandomUtil.randomNumbers(6));
            //添加用户默认头像
            user.setHeadImage("https://shengtangtouxiang.oss-cn-beijing.aliyuncs.com/moren.jpg");
            //机器人标识
            user.setType(1);
            users.add(user);
        }
        this.saveBatch(users);
        return Result.ok();
    }

    @Override
    public Map<Long, User> getUserListById(List<Long> userIds) {
        if(CollectionUtils.isEmpty(userIds)){
            return new HashMap<Long, User>();
        }
        List<User> users = baseMapper.selectBatchIds(userIds);
        if(CollectionUtils.isEmpty(users)){
            return new HashMap<Long, User>();
        }
        return users.stream().collect(Collectors.toMap(User::getId,user->user));
    }

    public static String generateRandomMobilePhoneNumber() {
        Random random = new Random();
        StringBuilder mobilePhoneNumber = new StringBuilder();
        // 第一位数字，固定是1
        mobilePhoneNumber.append('1');
        // 第二位数字，随机选择3-9中的一个
        char secondDigit = (char) ('3' + random.nextInt(7));
        mobilePhoneNumber.append(secondDigit);
        // 后面加上9位数字，0-9中随机选择
        for (int i = 0; i < 10; i++) {
            mobilePhoneNumber.append(random.nextInt(10));
        }
        return mobilePhoneNumber.toString();
    }


    public List<UserMayKnowVo> getMayKnowList(List<UserMayKnowVo> contact, Long userId) {
        // 为空直接返回空 2024/5/1 下午3:18 By Wesin
        if (contact.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取手机号列表 2024/5/1 下午3:18 By Wesin
        List<String> mobile = contact.stream().map(UserMayKnowVo::getMobile).collect(Collectors.toList());

        // 根据手机号查询用户 要求返回6个 2024/5/1 下午3:18 By Wesin
        List<User> userList = userMapper.selectMayKnowAndUnconcern(mobile, userId);

        // 组装分页后的返回数据 2024/5/1 下午3:19 By Wesin
        if (userList != null && !userList.isEmpty()) {
            // 用户封装成以手机号为key，user对象为value的map 2024/5/1 下午4:08 By Wesin 
            Map<String, User> userMap = userList.stream()
                    .collect(Collectors.toMap(User::getMobile, Function.identity()));
            
            // 遍历传入参数，匹配项设置user对象，不匹配项抛弃 2024/5/1 下午4:10 By Wesin 
            return contact.stream()
                    .filter(vo -> userMap.containsKey(vo.getMobile()))
                    .peek(vo -> vo.setUser(userMap.get(vo.getMobile())))
                    .collect(Collectors.toList());
        }
        
        // 查询不到联系人里边存在系统用户，直接返回空数组 2024/5/1 下午4:10 By Wesin
        return new ArrayList<>();
    }
}